<template>
  <div class="layout-container">
    <!-- 遮罩层 (移动端) -->
    <div 
      v-if="isMobileSiderVisible" 
      class="mobile-overlay"
      @click="hideMobileSider"
    ></div>
    
    <!-- 侧边栏 -->
    <LayoutSider :class="{ 'mobile-visible': isMobileSiderVisible }" />
    
    <!-- 主内容区 -->
    <div class="layout-main" :style="mainStyle">
      <!-- 头部 -->
      <LayoutHeader @toggle-mobile-sider="toggleMobileSider" />
      
      <!-- 页面内容 -->
      <div class="layout-content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import LayoutHeader from '@/components/Layout/LayoutHeader.vue'
import LayoutSider from '@/components/Layout/LayoutSider.vue'

const siderWidth = ref(240)
const isMobileSiderVisible = ref(false)

// 计算主内容区样式
const mainStyle = computed(() => {
  // 在移动端不设置 marginLeft
  if (window.innerWidth <= 768) {
    return {}
  }
  return { marginLeft: siderWidth.value + 'px' }
})

const handleSiderCollapse = (event) => {
  siderWidth.value = event.detail.collapsed ? 64 : 240
}

const toggleMobileSider = () => {
  isMobileSiderVisible.value = !isMobileSiderVisible.value
}

const hideMobileSider = () => {
  isMobileSiderVisible.value = false
}

onMounted(() => {
  document.addEventListener('sider-collapse', handleSiderCollapse)
})

onUnmounted(() => {
  document.removeEventListener('sider-collapse', handleSiderCollapse)
})
</script>

<style scoped lang="scss">
.layout-container {
  display: flex;
  height: 100vh; // 使用固定高度而不是min-height
  overflow: hidden; // 防止整个容器滚动
  background-color: #f5f7fa;
}

.layout-main {
  flex: 1;
  margin-left: 240px;
  display: flex;
  flex-direction: column;
  height: 100vh; // 使用固定高度
  overflow: hidden; // 防止main区域滚动
  transition: margin-left 0.3s ease; // 添加过渡效果
}

.layout-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto; // 只在内容区域滚动
  overflow-x: hidden;
  height: calc(100vh - 64px); // 减去header高度
}

// 移动端遮罩层
.mobile-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 98;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

// 平板适配 (768px - 1024px)
@media (max-width: 1024px) {
  .layout-content {
    padding: 16px;
  }
}

// 移动端适配 (<768px)
@media (max-width: 768px) {
  .layout-container {
    position: relative;
  }

  .mobile-overlay {
    display: block;
  }

  .layout-main {
    margin-left: 0 !important;
    width: 100%;
  }

  .layout-content {
    padding: 12px;
  }
}

// 小屏幕移动端 (<480px)
@media (max-width: 480px) {
  .layout-content {
    padding: 8px;
  }
}
</style>
